package tools.oracle;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.zhixiang.core.util.FileUtils;


public class DBUtils
{
    /**
     * 获得Oracle的安装根目录
     * @return
     */
    public static String getOracleHome(SessionFactory sessionFactory)
    {
        String oraclHome = System.getenv("ORACLE_HOME");
//        String oraclHome = "C:/ProgramData/Oracle/product/11.2.0/dbhome_1";
        if(StringUtils.isEmpty(oraclHome)){
            Session session = sessionFactory.openSession();
            SQLQuery sqlQuery = session.createSQLQuery("select directory_path from dba_directories where directory_name='LOG_FILE_DIR'");
            List list = sqlQuery.list();
            Object obj = list.get(0);
            oraclHome = String.valueOf(obj).replace("\\demo\\schema\\log\\","");
            session.close();
        }
        return oraclHome;
    }
    

    /**
     * 获得Oracle的安装根目录
     * @return
     */
    public static String getUserName(SessionFactory sessionFactory)
    {
        Session session = sessionFactory.openSession();
        SQLQuery sqlQuery = session.createSQLQuery("SELECT USERNAME FROM USER_USERS");
        List list = sqlQuery.list();
        Object obj = list.get(0);
        String userName = String.valueOf(obj);
        session.close();

        return userName;
    }

    public static Properties getProperties()
    {
        try {
            Properties properties = new Properties();
            String classPath = DBUtils.class.getResource("/").getPath().substring(1);
            properties.load(new FileInputStream(classPath + "/conf/jdbc.properties"));
            return properties;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUserName(Properties properties)
    {
        if(properties != null) {
            return properties.getProperty("jdbc.username");
        }else{
            return null;
        }
    }

    public static String getPassword(Properties properties)
    {
        if(properties != null) {
            return properties.getProperty("jdbc.password");
        }else{
            return null;
        }
    }


    /**
     * 用source命令导入存储过程
     * @param oracleHome
     * @param absoluteFilePath
     */
    public static void oracleImport(String oracleHome,String absoluteFilePath)
    {
        BufferedInputStream in = null;
        BufferedReader inBr = null;
        try
        {
            Properties properties = getProperties();
            String userName = getUserName(properties);
            String passord = getPassword(properties);
            oracleHome = oracleHome.replace("\\", "/");
            String cmd = "\"" + oracleHome + "/BIN/sqlplus\" "+userName+"/"+passord+" @" + absoluteFilePath;
            System.out.println(cmd);
            Runtime.getRuntime().exec(cmd);


        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (in != null)
            {
                try
                {
                    inBr.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 用source命令导入存储过程
     * @param oracleHome
     * @param absolutePath
     */
    public static void oracleImport(String oracleHome, String userName, String absolutePath)
    {
        BufferedInputStream in = null;
        BufferedReader inBr = null;
        try
        {
            Properties properties = getProperties();
            oracleHome = oracleHome.replace("\\", "/");
            String cmd = "\"" + oracleHome + "/BIN/sqlplus\" "+userName+"/123456 @"+absolutePath;
//            String cmd = "\"" + oracleHome + "/BIN/sqlplus\" "+userName+"/123456 @d:/test.sql";
            System.out.println(cmd);
            Runtime.getRuntime().exec(cmd);


        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (in != null)
            {
                try
                {
                    inBr.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 递归查找baseDir下所有目录中的sql文件
     */
    public static List<File> getFiles(File basefile)
    {
        List<File> fileList = new ArrayList<File>();
        File[] files = basefile.listFiles();
        for (File file : files)
        {
            if (file.isDirectory())
            {
                fileList.addAll(getFiles(file));
            }
            else if (file.isFile())
            {
                String extensionName = FileUtils.getExtensionName(file.getName());
                if ("sql".equalsIgnoreCase(extensionName))
                {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }
    
    /**
     * 递归查找baseDir下所有目录中的sql文件
     */
    public static List<File> getFiles(File basefile,String[] excludeFolder)
    {
        List<File> fileList = new ArrayList<File>();
        File[] files = basefile.listFiles();
        for (File file : files)
        {
            String fileName = file.getName();
            if (file.isDirectory())
            {
                if(!Arrays.asList(excludeFolder).contains(fileName)){
                    fileList.addAll(getFiles(file));
                }
            }
            else if (file.isFile())
            {
                String extensionName = FileUtils.getExtensionName(fileName);
                if ("sql".equalsIgnoreCase(extensionName))
                {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(DBUtils.class.getResource("/").getPath().substring(1));

        Properties properties = new Properties();
        String classPath = DBUtils.class.getResource("/").getPath().substring(1);
        properties.load(new FileInputStream(classPath + "/conf/jdbc.properties"));
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        System.out.println(username);
        System.out.println(password);

    }
}
